﻿// Copyright (c) 2011 Dan Popick

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Open.Web.Stijl;

namespace Open.Web.Stijl.Partitioning
{
	public class Set<T> : FactorSet, IEnumerable<T> where T : PartitionedItem
	{
		List<T> _items = new List<T>();

		public int SecondarySize { get; set; }
		public int Count { get { return _items.Count; } }
		public int Index { get; set; }

		public Set(int index)
			: base(new int[0], 1)
		{
			Index = index;
			SecondarySize = 0;
		}

		public Set(Set<T> newSet)
			: base(newSet)
		{
			Index = newSet.Index;
			_items = new List<T>(newSet._items);
			SecondarySize = newSet.SecondarySize;
		}

		public static Set<T> FromItem(int index, T item)
		{
			Set<T> set = new Set<T>(index);

			// it would be easier to call Add here, but add will fail on non-factorizable numbers.
			set.InitializeFromNumber(item.Size);
			set._items.Add(item);
			set.SecondarySize = item.SecondarySize;

			return set;
		}

		public override string Log(int indentChars)
		{
			string indent = new String(' ', indentChars);
			return String.Format("{0}Set: {1}, {2} : {3}",
				indent, Index, Size,
				String.Join(", ", _items.Select(x => x.Size.ToString()).ToArray()));
		}

		public void Add(T item)
		{
			base.Add(item);
			_items.Add(item);
			SecondarySize += item.SecondarySize;
		}

		public IEnumerator<T> GetEnumerator()
		{
			return _items.GetEnumerator();
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return _items.GetEnumerator();
		}
	}
}
